package web.servlets;

import domain.Account;
import domain.Cart;
import domain.Item;
import persistence.Impl.CartDAOImpl;
import service.CatelogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR="/WEB-INF/jsp/common/Error.jsp";

    private String workingItemId;
    private Cart cart;

    private CatelogService catalogService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CartDAOImpl cartDAO = new CartDAOImpl();
        workingItemId = req.getParameter("itemId");

        HttpSession session = req.getSession();
        if(session.getAttribute("username")!=null) {
            cart = (Cart) session.getAttribute("cart");
            Account account = (Account) session.getAttribute("account");
            Integer symbol = (Integer) session.getAttribute("symbol");

            if (cart == null) {
                cart = new Cart();
            }

            if (cart.containsItemId(workingItemId)) {
                if (symbol != 1) {
                    cart.incrementQuantityByItemId(workingItemId);
                    if (account != null) {
                        int ItemQuantity = cartDAO.getQuantityByItemIdAndUserName(account.getUsername(), workingItemId) + 1;
                        cartDAO.updateQuantityByUserName(account.getUsername(), workingItemId, ItemQuantity);
                    }
                }
            } else {
                catalogService = new CatelogService();
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item, isInStock);
                if (account != null) {
                    cartDAO.insertToCart(account.getUsername(), workingItemId);
                }
            }
            session.setAttribute("cart", cart);
            session.setAttribute("symbol", 1);
            req.getRequestDispatcher(VIEW_CART).forward(req, resp);
        }else{
            session.setAttribute("message","Please sign in before you use cart");
            req.getRequestDispatcher(ERROR).forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
